Imports System.IO
Imports System.Data.SqlClient
Imports System
Imports System.Text
Imports System.Security.Cryptography
Imports System.Runtime.InteropServices

Public Class FrmLogin
    Inherits System.Windows.Forms.Form
    Private Shared DES As New TripleDESCryptoServiceProvider()
    Private Shared MD5 As New MD5CryptoServiceProvider()
    ' Dim oFrmMain As New FrmMain()
#Region "Public constants"
    Public Const BSF_IGNORECURRENTTASK As Byte = 2 '&H2 'this ignores the current app
    Public Const BSF_POSTMESSAGE As Byte = 16 '&H10  'This posts the message
    Public Const BSM_APPLICATIONS As Byte = 8 '&H8  'This tells the windows message to just go to applications
#End Region

#Region "API imports"
    <DllImport("USER32.DLL", EntryPoint:="BroadcastSystemMessageA", _
       SetLastError:=True, CharSet:=CharSet.Unicode, _
       ExactSpelling:=True, _
       CallingConvention:=CallingConvention.StdCall)> _
    Public Shared Function BroadcastSystemMessage(ByVal dwFlags As Int32, ByRef pdwRecipients As Int32, ByVal uiMessage As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer
        ' Leave function empty - DLLImport attribute forwards calls to BroadcastSystemMessage to
        ' BroadcastSystemMessage in USER32.DLL.
    End Function
    <DllImport("USER32.DLL", EntryPoint:="RegisterWindowMessageA", _
       SetLastError:=True, CharSet:=CharSet.Unicode, _
       ExactSpelling:=True, _
       CallingConvention:=CallingConvention.StdCall)> _
    Public Shared Function RegisterWindowMessage(ByVal pString As String) As Integer
        ' Leave function empty - DLLImport attribute forwards calls to RegisterWindowMessage to
        ' RegisterWindowMessage in USER32.DLL.
    End Function
#End Region

#Region "Public Vars"
    Public MessageId As Integer  'This stores the unique windows message id from the registerwindowmessage call
#End Region

#Region "Private Vars"
    Private m_Mutex As System.Threading.Mutex 'Used to determine if the application is already open
    Private m_uniqueIdentifier As String = String.Empty 'user to determine if the app is already open
#End Region

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents Panel1 As System.Windows.Forms.Panel
    Friend WithEvents Panel2 As System.Windows.Forms.Panel
    Friend WithEvents lblUserName As System.Windows.Forms.Label
    Friend WithEvents Label1 As System.Windows.Forms.Label
    Friend WithEvents txtUserName As System.Windows.Forms.TextBox
    Friend WithEvents TxtPw As System.Windows.Forms.TextBox
    Friend WithEvents Label2 As System.Windows.Forms.Label
    Friend WithEvents btnLogin As System.Windows.Forms.Button
    Friend WithEvents btnCancel As System.Windows.Forms.Button
    Friend WithEvents lblErrLog As System.Windows.Forms.Label
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(FrmLogin))
        Me.Panel1 = New System.Windows.Forms.Panel
        Me.lblErrLog = New System.Windows.Forms.Label
        Me.Label2 = New System.Windows.Forms.Label
        Me.TxtPw = New System.Windows.Forms.TextBox
        Me.txtUserName = New System.Windows.Forms.TextBox
        Me.Label1 = New System.Windows.Forms.Label
        Me.lblUserName = New System.Windows.Forms.Label
        Me.Panel2 = New System.Windows.Forms.Panel
        Me.btnCancel = New System.Windows.Forms.Button
        Me.btnLogin = New System.Windows.Forms.Button
        Me.Panel1.SuspendLayout()
        Me.Panel2.SuspendLayout()
        Me.SuspendLayout()
        '
        'Panel1
        '
        Me.Panel1.BackColor = System.Drawing.Color.FromArgb(CType(CType(224, Byte), Integer), CType(CType(224, Byte), Integer), CType(CType(224, Byte), Integer))
        Me.Panel1.Controls.Add(Me.lblErrLog)
        Me.Panel1.Controls.Add(Me.Label2)
        Me.Panel1.Controls.Add(Me.TxtPw)
        Me.Panel1.Controls.Add(Me.txtUserName)
        Me.Panel1.Controls.Add(Me.Label1)
        Me.Panel1.Controls.Add(Me.lblUserName)
        Me.Panel1.Dock = System.Windows.Forms.DockStyle.Fill
        Me.Panel1.Font = New System.Drawing.Font("Verdana", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Panel1.Location = New System.Drawing.Point(0, 0)
        Me.Panel1.Name = "Panel1"
        Me.Panel1.Size = New System.Drawing.Size(370, 170)
        Me.Panel1.TabIndex = 0
        '
        'lblErrLog
        '
        Me.lblErrLog.ForeColor = System.Drawing.Color.Red
        Me.lblErrLog.Location = New System.Drawing.Point(8, 100)
        Me.lblErrLog.Name = "lblErrLog"
        Me.lblErrLog.Size = New System.Drawing.Size(360, 24)
        Me.lblErrLog.TabIndex = 5
        '
        'Label2
        '
        Me.Label2.BackColor = System.Drawing.Color.FromArgb(CType(CType(128, Byte), Integer), CType(CType(128, Byte), Integer), CType(CType(255, Byte), Integer))
        Me.Label2.Dock = System.Windows.Forms.DockStyle.Top
        Me.Label2.Font = New System.Drawing.Font("Verdana", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Label2.ForeColor = System.Drawing.Color.White
        Me.Label2.Location = New System.Drawing.Point(0, 0)
        Me.Label2.Name = "Label2"
        Me.Label2.Size = New System.Drawing.Size(370, 24)
        Me.Label2.TabIndex = 4
        Me.Label2.Text = "Breast Tumor Board"
        Me.Label2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
        '
        'TxtPw
        '
        Me.TxtPw.Location = New System.Drawing.Point(151, 64)
        Me.TxtPw.Name = "TxtPw"
        Me.TxtPw.PasswordChar = Global.Microsoft.VisualBasic.ChrW(42)
        Me.TxtPw.Size = New System.Drawing.Size(128, 21)
        Me.TxtPw.TabIndex = 2
        '
        'txtUserName
        '
        Me.txtUserName.Location = New System.Drawing.Point(151, 40)
        Me.txtUserName.Name = "txtUserName"
        Me.txtUserName.Size = New System.Drawing.Size(128, 21)
        Me.txtUserName.TabIndex = 1
        '
        'Label1
        '
        Me.Label1.Location = New System.Drawing.Point(70, 64)
        Me.Label1.Name = "Label1"
        Me.Label1.Size = New System.Drawing.Size(104, 16)
        Me.Label1.TabIndex = 1
        Me.Label1.Text = "Password"
        '
        'lblUserName
        '
        Me.lblUserName.Location = New System.Drawing.Point(70, 40)
        Me.lblUserName.Name = "lblUserName"
        Me.lblUserName.Size = New System.Drawing.Size(104, 16)
        Me.lblUserName.TabIndex = 0
        Me.lblUserName.Text = "User Name"
        '
        'Panel2
        '
        Me.Panel2.BackColor = System.Drawing.Color.Gray
        Me.Panel2.Controls.Add(Me.btnCancel)
        Me.Panel2.Controls.Add(Me.btnLogin)
        Me.Panel2.Dock = System.Windows.Forms.DockStyle.Bottom
        Me.Panel2.Location = New System.Drawing.Point(0, 130)
        Me.Panel2.Name = "Panel2"
        Me.Panel2.Size = New System.Drawing.Size(370, 40)
        Me.Panel2.TabIndex = 1
        '
        'btnCancel
        '
        Me.btnCancel.BackColor = System.Drawing.Color.Silver
        Me.btnCancel.Location = New System.Drawing.Point(288, 8)
        Me.btnCancel.Name = "btnCancel"
        Me.btnCancel.Size = New System.Drawing.Size(72, 24)
        Me.btnCancel.TabIndex = 1
        Me.btnCancel.Text = "Cancel"
        Me.btnCancel.UseVisualStyleBackColor = False
        '
        'btnLogin
        '
        Me.btnLogin.BackColor = System.Drawing.Color.Silver
        Me.btnLogin.ForeColor = System.Drawing.Color.Black
        Me.btnLogin.Location = New System.Drawing.Point(208, 8)
        Me.btnLogin.Name = "btnLogin"
        Me.btnLogin.Size = New System.Drawing.Size(72, 24)
        Me.btnLogin.TabIndex = 0
        Me.btnLogin.Text = "Login"
        Me.btnLogin.UseVisualStyleBackColor = False
        '
        'FrmLogin
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(6, 14)
        Me.ClientSize = New System.Drawing.Size(370, 170)
        Me.Controls.Add(Me.Panel2)
        Me.Controls.Add(Me.Panel1)
        Me.Font = New System.Drawing.Font("Verdana", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog
        Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
        Me.MaximizeBox = False
        Me.MinimizeBox = False
        Me.Name = "FrmLogin"
        Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
        Me.Text = "Login "
        Me.Panel1.ResumeLayout(False)
        Me.Panel1.PerformLayout()
        Me.Panel2.ResumeLayout(False)
        Me.ResumeLayout(False)

    End Sub

#End Region

    Public Shared Function MD5Hash(ByVal value As String) As Byte()
        Return MD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(value))
    End Function

    Public Shared Function Encrypt(ByVal stringToEncrypt As String, ByVal key As String) As String
        DES.Key = FrmLogin.MD5Hash(key)
        DES.Mode = CipherMode.ECB
        Dim Buffer As Byte() = ASCIIEncoding.ASCII.GetBytes(stringToEncrypt)
        Return Convert.ToBase64String(DES.CreateEncryptor().TransformFinalBlock(Buffer, 0, Buffer.Length))
    End Function

    Public Shared Function Decrypt(ByVal encryptedString As String, ByVal key As String) As String

        'Try
        'DES.Key = FrmLogin.MD5Hash(key)
        'DES.Mode = CipherMode.ECB
        'Dim Buffer As Byte() = Convert.FromBase64String(encryptedString)
        'Return ASCIIEncoding.ASCII.GetString(DES.CreateDecryptor().TransformFinalBlock(Buffer, 0, Buffer.Length))
        'Catch ex As Exception
        ' MessageBox.Show("Invalid Key", "Decryption Failed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        'End Try
    End Function

    Private Sub CheckApp()
        If (UBound(Process.GetProcessesByName(Process.GetCurrentProcess.ProcessName)) > 0) Then End
    End Sub

    Private Sub GetConnectionStr()
        'get connection string
        Dim x As New INIAccess()
        Dim vServerName, vDataBase, vuser, vPw As String
        Dim decrypt_vServerName, decrypt_vDataBase, decrypt_vuser, decrypt_vPw As String
        Dim vCmd, vImportAllow As String
        vServerName = x.INIRead(Application.StartupPath & "\ncc.ini", "DB_CONNECTION", "SERVER_NM", "")
        vDataBase = x.INIRead(Application.StartupPath & "\ncc.ini", "DB_CONNECTION", "DATABASE", "")
        vuser = x.INIRead(Application.StartupPath & "\ncc.ini", "DB_CONNECTION", "USER_NM", "")
        vPw = x.INIRead(Application.StartupPath & "\ncc.ini", "DB_CONNECTION", "Password", "")

        '----------------------------
        ' Decrypt connetion string
        '----------------------------
        
        'decrypt_vServerName = Decrypt(vServerName)
        'decrypt_vDataBase = Decrypt(vDataBase)
        'decrypt_vuser = Decrypt(vuser)
        'decrypt_vPw = Decrypt(vPw)
        Dim sConnectionString As String
        If (
            vServerName.Equals("RAsSj41XyBOT1RkkcHN+ug") And
            vDataBase.Equals("JLlXsUTgZ6ksS/x9tfElZA") And
            vuser.Equals("ORfksXMtsqfMVnPGRPI5uw") And
            vPw.Equals("/mVbpfAkoFHkq1ChS1vaPA")
           ) Then
            sConnectionString = "server=ncdata02;uid=sa;pwd=lifebook;database=BTB2"
        Else
            sConnectionString = ""
        End If



        'Dim sConnectionString As String = "server=ncdata02;uid=sa;pwd=lifebook;database=btb2"
        GV_CONNETION = sConnectionString

    End Sub
    Private Sub Login()

        

        Dim myCommand As SqlCommand
        Dim SqlConn As New SqlConnection()
        SqlConn = New SqlConnection(GV_CONNETION)
        myCommand = New SqlCommand("spLogin", SqlConn)
        myCommand.CommandType = CommandType.StoredProcedure
        SqlConn.Open()

        myCommand.Parameters.Add("@USERID", SqlDbType.VarChar)
        myCommand.Parameters.Add("@PW", SqlDbType.Binary, 16)
        myCommand.Parameters("@USERID").Value = Trim(txtUserName.Text)
        myCommand.Parameters("@PW").Value = GenerateMD5_Pw(Trim(TxtPw.Text))

        Dim strSPOut As String
        strSPOut = myCommand.ExecuteScalar()
        If strSPOut <> "PASS" Then
            lblErrLog.Visible = True
            lblErrLog.Text = strSPOut
        Else
            lblErrLog.Visible = False
            TxtPw.Text = ""
            GV_USER = GetUserID(Trim(txtUserName.Text)) 'UCase(Trim(txtUserName.Text))
            GV_USERLOGINID = Trim(txtUserName.Text)
            GetUserName()
            GetUserRight()
            InsertAuditLog()
            If GV_VIEW_ONLY = False Then
                MsgBox("Access denied. Unauthorized user.", MsgBoxStyle.Information, "ATU Scan Appointment System")
                Exit Sub
            Else
                Dim oFrmMain As New FrmMain()
                oFrmMain.Show()
                Me.Hide()
            End If
        End If
     
    End Sub
    Function GetUserID(ByVal vUseLoginID)

        Dim SqlConnection1 As New SqlConnection()
        SqlConnection1 = New SqlConnection(GV_CONNETION)
        If SqlConnection1.State = ConnectionState.Closed Then SqlConnection1.Open()
        Dim sqlCmd = New SqlCommand("spGetUserID", SqlConnection1)
        sqlCmd.Parameters.Add("@UserLoginID", SqlDbType.VarChar)
        sqlCmd.Parameters("@UserLoginID").Value = vUseLoginID
        sqlCmd.CommandType = CommandType.StoredProcedure
        Dim rsReader As SqlDataReader
        rsReader = sqlCmd.ExecuteReader()
        If rsReader.Read() Then
            GetUserID = IIf(IsDBNull(rsReader("UserID")), "0", rsReader("UserID"))
        End If
        rsReader.Close()
        SqlConnection1.Close()
    End Function
    Private Sub InsertAuditLog()
        Try
            Dim myCommand As SqlCommand
            Dim vSQL As String
            'Response.Write(e.Item.Cells(4).Text)
            'CONNETION STRING
            Dim SqlConn As New SqlConnection()
            SqlConn = New SqlConnection(GV_CONNETION)
            myCommand = New SqlCommand("spInsertAuditLog", SqlConn)
            myCommand.CommandType = CommandType.StoredProcedure
            SqlConn.Open()

            myCommand.Parameters.Add("@UserId", SqlDbType.VarChar)
            myCommand.Parameters.Add("@STATUS", SqlDbType.VarChar)
            myCommand.Parameters("@UserId").Value = GV_USER
            myCommand.Parameters("@STATUS").Value = "IN"
            myCommand.ExecuteNonQuery()
            myCommand.Cancel()
            SqlConn.Close()
            myCommand = Nothing
            SqlConn = Nothing

        Catch ex As Exception
            Dim vStrErr As String
            vStrErr = ex.Message & " ||InsertAuditLog||"
            Write_ErrLog(vStrErr)
            Exit Sub
        End Try

    End Sub

    Private Sub Write_ErrLog(ByVal vStrErr)
        'Write error log into errlog.txt
        Dim strAppPath
        strAppPath = Mid(Application.ExecutablePath, 1, InStrRev(Application.ExecutablePath, "\") - 1)

        Dim myStreamWriter As New System.IO.StreamWriter(strAppPath & "\Errlog.txt", True)
        myStreamWriter.WriteLine(Now & "  " & vStrErr)
        myStreamWriter.Flush()
        myStreamWriter.Close()
    End Sub

    Private Sub GetUserRight()
        'Dim SqlConnection1 As New SqlConnection()
        'SqlConnection1 = New SqlConnection(GV_CONNETION)
        'If SqlConnection1.State = ConnectionState.Closed Then SqlConnection1.Open()
        'Dim sqlCmd = New SqlCommand("spGetUserRight", SqlConnection1)
        'sqlCmd.Parameters.Add("@STAFF_ID", SqlDbType.VarChar)
        'sqlCmd.Parameters("@STAFF_ID").Value = GV_USER
        'sqlCmd.CommandType = CommandType.StoredProcedure
        'Dim rsReader As SqlDataReader
        'rsReader = sqlCmd.ExecuteReader()
        'If rsReader.Read() Then
        '    GV_VIEW_ONLY = IIf(IsDBNull(rsReader("Sec_View")), "TRUE", rsReader("Sec_View"))
        '    GV_ALLOW_EDIT = IIf(IsDBNull(rsReader("Sec_Modify")), "FALSE", rsReader("Sec_Modify"))
        '    GV_ALLOW_DELETE = IIf(IsDBNull(rsReader("Sec_Delete")), "FALSE", rsReader("Sec_Delete"))
        '    GV_ALLOW_PRINT = IIf(IsDBNull(rsReader("Sec_Print")), "FALSE", rsReader("Sec_Print"))
        'End If
        'rsReader.Close()
        'SqlConnection1.Close()
        GV_VIEW_ONLY = True
        GV_ALLOW_EDIT = True
        GV_ALLOW_DELETE = True
        GV_ALLOW_PRINT = True
    End Sub
    Private Sub GetUserName()

        Dim SqlConnection1 As New SqlConnection()
        SqlConnection1 = New SqlConnection(GV_CONNETION)
        If SqlConnection1.State = ConnectionState.Closed Then SqlConnection1.Open()
        Dim sqlCmd = New SqlCommand("spGetUserName", SqlConnection1)
        sqlCmd.Parameters.Add("@STAFF_ID", SqlDbType.VarChar)
        sqlCmd.Parameters("@STAFF_ID").Value = GV_USER
        sqlCmd.CommandType = CommandType.StoredProcedure
        Dim rsReader As SqlDataReader
        rsReader = sqlCmd.ExecuteReader()
        If rsReader.Read() Then
            GV_USERNAME = IIf(IsDBNull(rsReader("UserName")), "", rsReader("UserName"))
        End If
        rsReader.Close()
        SqlConnection1.Close()
    End Sub

    Function GenerateMD5_Pw(ByVal vb4EncryptPW) As Byte()
        Dim md5Hasher As New MD5CryptoServiceProvider()

        Dim hashedBytes As Byte()
        Dim encoder As New UTF8Encoding()

        hashedBytes = md5Hasher.ComputeHash(encoder.GetBytes(vb4EncryptPW))
        GenerateMD5_Pw = hashedBytes


    End Function

    Shared Function GetMd5Hash(ByVal md5Hash As MD5, ByVal input As String) As String

        ' Convert the input string to a byte array and compute the hash. 
        Dim data As Byte() = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input))

        ' Create a new Stringbuilder to collect the bytes 
        ' and create a string. 
        Dim sBuilder As New StringBuilder()

        ' Loop through each byte of the hashed data  
        ' and format each one as a hexadecimal string. 
        Dim i As Integer
        For i = 0 To data.Length - 1
            sBuilder.Append(data(i).ToString("x2"))
        Next i

        ' Return the hexadecimal string. 
        Return sBuilder.ToString()

    End Function 'GetMd5Hash


    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        End
    End Sub

    Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
        Login()
    End Sub

    Private Sub TxtPw_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TxtPw.TextChanged

    End Sub

    Private Sub TxtPw_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TxtPw.KeyDown
        If e.KeyValue = 13 Then
            Login()
        End If
    End Sub

    Private Sub FrmLogin_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Try
            checkprevious()
            GetConnectionStr()
            ReceivePara()
            GV_VALID_USER = False
            GV_ISFROM_EXTERNAL = False
            If GV_USER <> "" Then
                If IsValidUser(GV_USER) Then
                    GV_VALID_USER = True
                    GV_ISFROM_EXTERNAL = True
                    GetUserName()
                    GetUserRight()
                    InsertAuditLog()
                    If GV_VIEW_ONLY = False Then
                        MsgBox("Access denied. Unauthorized user.", MsgBoxStyle.Information, "Breast Tumor Board")
                        Exit Sub
                    Else
                        Dim oFrmMain As New FrmMain()
                        oFrmMain.Show()
                        Me.Hide()
                    End If
                Else
                    txtUserName.Text = GV_USER
                End If
            End If
        Catch ex As Exception
            Dim vStrErr As String
            vStrErr = ex.Message & " ||FrmLogin_Load||"
            Write_ErrLog(vStrErr)
            MsgBox("Login fail.", MsgBoxStyle.Information, "Login")
            Exit Sub
        End Try

    End Sub


    Private Function IsValidUser(ByVal GV_USER) As Boolean
        Try
            Dim vStatus As String
            Dim SqlConnection1 As New SqlConnection()
            SqlConnection1 = New SqlConnection(GV_CONNETION)
            If SqlConnection1.State = ConnectionState.Closed Then SqlConnection1.Open()
            Dim sqlCmd = New SqlCommand("spIsValidUser", SqlConnection1)
            sqlCmd.Parameters.Add("@USER_ID", SqlDbType.VarChar)
            sqlCmd.Parameters("@USER_ID").Value = GV_USER
            sqlCmd.CommandType = CommandType.StoredProcedure
            Dim rsReader As SqlDataReader
            rsReader = sqlCmd.ExecuteReader()
            If rsReader.Read() Then
                vStatus = IIf(IsDBNull(rsReader("STATUS")), "NO", rsReader("STATUS"))
            End If
            rsReader.Close()
            SqlConnection1.Close()

            If Trim(UCase(vStatus)) = "OK" Then
                IsValidUser = True
            Else
                IsValidUser = False
            End If

        Catch ex As Exception
            Dim vStrErr As String
            vStrErr = ex.Message & " ||IsValidUser||"
            Write_ErrLog(vStrErr)
            MsgBox("Invalid user.", MsgBoxStyle.Information, "Login")
            Exit Function
        End Try
    End Function


    Private Sub ReceivePara()
        '...command line arguments received when load app.
        GV_USER = ""
        Dim i As Integer
        For i = 0 To Environment.GetCommandLineArgs().Length - 1
            'Console.WriteLine(Environment.GetCommandLineArgs(i))
            If Mid(UCase(Environment.GetCommandLineArgs(i)), 1, 4) = "UID:" Then
                GV_USER = Mid(UCase(Environment.GetCommandLineArgs(i)), 5, Len(Environment.GetCommandLineArgs(i)))
            End If
        Next i
    End Sub

    Protected Overrides Sub DefWndProc(ByRef m As System.Windows.Forms.Message)
        'This overrides the windows messaging processing
        If m.Msg = MessageId Then 'If we found our message then activate
            ' Set the WindowState to normal if the form is minimized.
            If (Me.WindowState = FormWindowState.Minimized) Then
                Me.Show()
                Me.WindowState = FormWindowState.Normal
            End If

            ' Activate the form.
            Me.Activate()
            Me.Focus()
            'MsgBox("ok")
        Else 'Let the normal windows messaging process it.
            MyBase.DefWndProc(m)
        End If


    End Sub

    ' This method checks to see if the app is already running.
    Private Sub checkprevious()
        'Check for previous instance of this app
        m_uniqueIdentifier = Application.ExecutablePath.Replace("\", "_")
        m_Mutex = New System.Threading.Mutex(False, m_uniqueIdentifier)
        'First register the windows message
        MessageId = RegisterWindowMessage(m_uniqueIdentifier)
        If m_Mutex.WaitOne(1, True) Then
            'we are the first instance don't need to do anything

        Else
            'Cause the current form to show
            'Now brodcast a message to cause the first instance to show up
            Dim BSMRecipients As Int32 = BSM_APPLICATIONS 'Only go to applications

            Dim tmpuint32 As Int32 = 0
            tmpuint32 = tmpuint32 Or BSF_IGNORECURRENTTASK 'Ignore current app
            tmpuint32 = tmpuint32 Or BSF_POSTMESSAGE 'Post the windows message
            Dim ret As Integer
            ret = BroadcastSystemMessage(tmpuint32, BSMRecipients, MessageId, 0, 0)
            'A differnt instance already exists exit now.
            Application.Exit()
        End If
    End Sub

    Private Sub FrmLogin_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Activated
        If GV_VALID_USER = True Then Me.Hide()
    End Sub



    Private Function Encrypt(ByVal plainText As String) As String
        Dim passPhrase As String = "yourPassPhrase"
        Dim saltValue As String = "mySaltValue"
        Dim hashAlgorithm As String = "SHA1"
        Dim passwordIterations As Integer = 2
        Dim initVector As String = "@1B2c3D4e5F6g7H8"
        Dim keySize As Integer = 256
        Dim initVectorBytes As Byte() = Encoding.ASCII.GetBytes(initVector)
        Dim saltValueBytes As Byte() = Encoding.ASCII.GetBytes(saltValue)
        Dim plainTextBytes As Byte() = Encoding.UTF8.GetBytes(plainText)
        Dim password As New PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations)
        Dim keyBytes As Byte() = password.GetBytes(keySize \ 8)
        Dim symmetricKey As New RijndaelManaged()
        symmetricKey.Mode = CipherMode.CBC
        Dim encryptor As ICryptoTransform = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes)
        Dim memoryStream As New MemoryStream()
        Dim cryptoStream As New CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)
        cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length)
        cryptoStream.FlushFinalBlock()
        Dim cipherTextBytes As Byte() = memoryStream.ToArray()
        memoryStream.Close()
        cryptoStream.Close()
        Dim cipherText As String = Convert.ToBase64String(cipherTextBytes)
        Return cipherText
    End Function


    Private Function Decrypt(ByVal cipherText As String) As String
        Dim passPhrase As String = "yourPassPhrase"
        Dim saltValue As String = "mySaltValue"
        Dim hashAlgorithm As String = "SHA1"
        Dim passwordIterations As Integer = 2
        Dim initVector As String = "@1B2c3D4e5F6g7H8"
        Dim keySize As Integer = 256
        ' Convert strings defining encryption key characteristics into byte
        ' arrays. Let us assume that strings only contain ASCII codes.
        ' If strings include Unicode characters, use Unicode, UTF7, or UTF8
        ' encoding.
        Dim initVectorBytes As Byte() = Encoding.ASCII.GetBytes(initVector)
        Dim saltValueBytes As Byte() = Encoding.ASCII.GetBytes(saltValue)
        ' Convert our ciphertext into a byte array.
        Dim cipherTextBytes As Byte()
        Try
            cipherTextBytes = Convert.FromBase64String(cipherText)
        Catch ex As Exception
            Console.WriteLine(ex.StackTrace)
        End Try

        ' First, we must create a password, from which the key will be
        ' derived. This password will be generated from the specified
        ' passphrase and salt value. The password will be created using
        ' the specified hash algorithm. Password creation can be done in
        ' several iterations.
        Dim password As New PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations)
        ' Use the password to generate pseudo-random bytes for the encryption
        ' key. Specify the size of the key in bytes (instead of bits).
        Dim keyBytes As Byte() = password.GetBytes(keySize \ 8)
        ' Create uninitialized Rijndael encryption object.
        Dim symmetricKey As New RijndaelManaged()
        ' It is reasonable to set encryption mode to Cipher Block Chaining
        ' (CBC). Use default options for other symmetric key parameters.
        symmetricKey.Mode = CipherMode.CBC
        ' Generate decryptor from the existing key bytes and initialization
        ' vector. Key size will be defined based on the number of the key
        ' bytes.
        Dim decryptor As ICryptoTransform = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes)
        ' Define memory stream which will be used to hold encrypted data.
        Dim memoryStream As New MemoryStream(cipherTextBytes)
        ' Define cryptographic stream (always use Read mode for encryption).
        Dim cryptoStream As New CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)
        ' Since at this point we don't know what the size of decrypted data
        ' will be, allocate the buffer long enough to hold ciphertext;
        ' plaintext is never longer than ciphertext.
        Dim plainTextBytes As Byte() = New Byte(cipherTextBytes.Length - 1) {}
        ' Start decrypting.
        Dim decryptedByteCount As Integer = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length)
        ' Close both streams.
        memoryStream.Close()
        cryptoStream.Close()
        ' Convert decrypted data into a string.
        ' Let us assume that the original plaintext string was UTF8-encoded.
        Dim plainText As String = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount)
        ' Return decrypted string.



        Return plainText
    End Function



End Class
Public Class INIAccess
#Region "API Calls"
    ' standard API declarations for INI access
    Private Declare Unicode Function WritePrivateProfileString _
                            Lib "kernel32" _
                            Alias "WritePrivateProfileStringW" _
                            (ByVal lpApplicationName As String, _
                             ByVal lpKeyName As String, _
                             ByVal lpString As String, _
                             ByVal lpFileName As String) As Int32
    Private Declare Unicode Function GetPrivateProfileString _
                            Lib "kernel32" _
                            Alias "GetPrivateProfileStringW" _
                            (ByVal lpApplicationName As String, _
                             ByVal lpKeyName As String, _
                             ByVal lpDefault As String, _
                             ByVal lpReturnedString As String, _
                             ByVal nSize As Int32, _
                             ByVal lpFileName As String) As Int32
#End Region

#Region "--- INIRead ---"
    Public Overloads Function INIRead(ByVal INIPath As String, ByVal SectionName As String, ByVal KeyName As String, ByVal DefaultValue As String) As String
        ' primary version of call gets single value given all parameters
        Dim n As Int32
        Dim sData As String

        sData = Space$(1024) ' allocate some room 
        n = GetPrivateProfileString(SectionName, KeyName, DefaultValue, sData, sData.Length, INIPath)
        If n > 0 Then ' return whatever it gave us
            INIRead = sData.Substring(0, n)
        Else
            INIRead = ""
        End If
    End Function

    Public Overloads Function INIRead(ByVal INIPath As String, _
      ByVal SectionName As String, ByVal KeyName As String) As String
        ' overload 1 assumes zero-length default
        Return INIRead(INIPath, SectionName, KeyName, "")
    End Function

    Public Overloads Function INIRead(ByVal INIPath As String, ByVal SectionName As String) As String
        ' overload 2 returns all keys in a given section of the given file
        Return INIRead(INIPath, SectionName, Nothing, "")
    End Function

    Public Overloads Function INIRead(ByVal INIPath As String) As String
        ' overload 3 returns all section names given just path
        Return INIRead(INIPath, Nothing, Nothing, "")
    End Function
#End Region

#Region "--- INIWrite ---"
    Public Sub INIWrite(ByVal INIPath As String, ByVal SectionName As String, ByVal KeyName As String, ByVal TheValue As String)
        Call WritePrivateProfileString(SectionName, KeyName, TheValue, INIPath)
    End Sub
#End Region

#Region "--- INIDelete ---"
    Public Overloads Sub INIDelete(ByVal INIPath As String, ByVal SectionName As String, ByVal KeyName As String)       ' delete single line from section
        Call WritePrivateProfileString(SectionName, KeyName, Nothing, INIPath)
    End Sub

    Public Overloads Sub INIDelete(ByVal INIPath As String, ByVal SectionName As String)
        ' delete section from INI file
        Call WritePrivateProfileString(SectionName, Nothing, Nothing, INIPath)
    End Sub
#End Region
End Class